import {storage} from "../../utils/common";
import router from "../../router";

const common = {
  state: {
    sideBarStatus: storage().get("sideBarStatus") || 0, // sidebar 开关状态
    tabs: storage().get("tabs") || [], // 顶部窗口标签
  },
  getters: {
    sideBarStatus: state => {
      return state.sideBarStatus
    },
    tabs: state => {
      return state.tabs
    }
  },
  mutations: {
    /**
     * 设置sideBar是否折叠
     * @param state
     */
    toggleSideBar: (state) => {
      if (state.sideBarStatus === 0) {
        state.sideBarStatus = 1
      } else {
        state.sideBarStatus = 0
      }
      storage().set("sideBarStatus",state.sideBarStatus)
    },
    /**
     * 添加tab标签页
     * @param state
     * @param tab
     */
    appendTab: (state, tab) => {
      let isExist = false
      // 判断标签页是否存在
      for (let i in state.tabs) {
        let item = state.tabs[i]
        if (item.path === tab.path) {
          isExist = true
          break
        }
      }
      // 若果不存在则往tab中插入数据
      if (isExist === false) {
        state.tabs.push(tab)
        storage().set("tabs", state.tabs)
      }
    },
    /**
     * 移出指定tab标签页
     * @param state
     * @param index
     */
    removeTab: (state, path) => {
      if (state.tabs.length < 2) return
      let tabIndex = 0
      // 判断标签页是否存在
      for (let i in state.tabs) {
        let item = state.tabs[i]
        if (item.path === path) {
          tabIndex = i
          break
        }
      }
      state.tabs.splice(tabIndex, 1)
      storage().set("tabs", state.tabs)
      let prevPath = state.tabs[state.tabs.length - 1].path
      if(router.app.$route.path === prevPath) return;
      else router.replace(state.tabs[state.tabs.length - 1].path)
    },
    /**
     * 移出所有的tab标签页
     * @param state
     */
    removeAllTab: (state) => {
      state.tabs = []
      storage().set("tabs", state.tabs)
    }
  },
  actions: {
    /**
     * 设置sidebar是否折叠
     * @param commit
     */
    toggleSideBar({commit}) {
      commit('toggleSideBar')
    },
    /**
     * 添加tab标签页
     * @param commit
     * @param tab
     */
    appendTab({commit}, tab) { // 增加tab
      commit('appendTab', tab)
    },
    /**
     * 移出指定tab标签页
     * @param commit
     * @param index
     */
    removeTab({commit}, path) { //
      commit('removeTab', path)
    },
    /**
     * 移出所有tab标签页
     * @param commit
     */
    removeAllTab({commit}) {
      return new Promise(resolve => {
        commit('removeAllTab')
        resolve()
      })
    },
  }
}
export default common
